import {defineNuxtPlugin} from '#app'

const configRouter = (() => {
    let done = false
    return () => {
        if (done) {
            return
        }
        done = true

        /*---------------------------------------加载微信jssdk-------------------------------------------*/
        const el = document.createElement('script') as HTMLScriptElement
        el.src = 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js'
        document.body.appendChild(el)

        /*---------------------------------------在路由守卫中处理跳转小程序页面的逻辑-------------------------------------------*/
        const router = useRouter()
        router.beforeEach((to, from) => {

            /*跳转商品详情，并且当前是小程序，走小程序跳转*/
            if (to.name === 'pdp-id') {
                const Win = window as any
                const {__wxjs_environment, wx} = Win
                if (__wxjs_environment === 'miniprogram') {
                    wx.miniProgram.navigateTo({url: `/pages/cms/cms-detail?id=${to.params.id}`})
                    return false
                }
            }
        })
    }
})()

export default defineNuxtPlugin(() => {
    configRouter()
})